iT邦幫忙

2025 iThome 鐵人賽

DAY 18
0
Vue.js

Vue.js 新手入門之路系列 第 18

Vue.js 新手入門之路 - props

  • 分享至 

  • xImage
  •  

延續上一篇 props
我們可以傳遞靜態或動態的 props
靜態 Props 傳遞的值就會是字串,不會解譯成表達式。

<BlogPost title="My journey with Vue" />

**動態 Props **則使用 v-bind -> 可以傳表達式。

<BlogPost :title="post.title" />
<BlogPost :title="post.title + ' by ' + post.author.name" />

不只字串, props 可以傳遞各種資料型別

<script setup>
import BlogPost from './components/props.vue'

const post = {
  title: '深入學習 Vue 3',
  likes: 123,
  isPublished: true,
  commentIds: [101, 102, 103],
  author: {
    name: 'Charlie',
    company: 'OpenAI'
  }
}
</script>

<template>
  <h1>文章列表</h1>

  <!-- 靜態 props -->
  <BlogPost
    title="我的 Vue 學習之旅"
    :likes="42"
    is-published
    :comment-ids="[234, 266, 273]"
    :author="{ name: 'Veronica', company: 'Veridian Dynamics' }"
  />

  <!-- 動態 props -->
  <BlogPost
    :title="post.title"
    :likes="post.likes"
    :is-published="post.isPublished"
    :comment-ids="post.commentIds"
    :author="post.author"
  />
</template>shed="post.isPublished" />

字串 布林 陣列 物件都可以

<script setup>
const props = defineProps({
  title: String,
  likes: Number,
  isPublished: Boolean,
  commentIds: Array,
  author: Object
})
</script>

<template>
  <div class="post">
    <h2>{{ title }}</h2>
    <p>👍 {{ likes }} likes</p>
    <p v-if="isPublished"> posted </p>
    <p v-else> draft </p>
    <p>comment id:{{ commentIds }}</p>
    <p>author:{{ author.name }} @ {{ author.company }}</p>
  </div>
</template>

<style scoped>
.post{
    text-align: center;
    justify-content: center;
    font-size: x-large;
    border: solid;
    margin-left: 450px;
    margin-top: 5px;
    height: 400px;
    width: 350px;
    padding: 35px;
}
</style>

ref:
https://zh-hk.vuejs.org/guide/components/props.html#prop-validation


上一篇
Vue.js 新手入門之路 - 元件化
系列文
Vue.js 新手入門之路18
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言